const app = getApp()
const financeBill = require('../../../utils/finance-bill')
Page({
  data: {
    // 账单选择器
    showBillSelector: false,
    billList: [],
    selectedBill: {},
    selectedBillIndex: 0, // 新增
    
    // Tab切换
    activeTab: 'pending',
    
    // 日期选择
    selectedDate: '',
    selectedYear: '',
    selectedMonth: '',
    
    // 记录列表
    recordList: [],
    loading: false,
    refreshing: false,
    pageNum: 1,
    pageSize: 8,
    hasMore: true,
    mockRecordList: [
      {
        id: '1',
        type: 'expense',
        category: '餐饮',
        description: '午餐',
        amount: '25.50',
        date: '2024-01-15',
        tags: ['日常', '餐饮']
      },
      {
        id: '2',
        type: 'income',
        category: '工资',
        description: '月薪',
        amount: '8000.00',
        date: '2024-01-10',
        tags: ['收入', '工资']
      },
      {
        id: '3',
        type: 'expense',
        category: '交通',
        description: '地铁',
        amount: '6.00',
        date: '2024-01-15',
        tags: ['日常', '交通']
      },
      {
        id: '4',
        type: 'expense',
        category: '购物',
        description: '衣服',
        amount: '299.00',
        date: '2024-01-14',
        tags: ['购物', '服装']
      },
      {
        id: '5',
        type: 'income',
        category: '兼职',
        description: '设计稿费',
        amount: '500.00',
        date: '2024-01-12',
        tags: ['收入', '兼职']
      },
      {
        id: '6',
        type: 'expense',
        category: '娱乐',
        description: '电影票',
        amount: '45.00',
        date: '2024-01-13',
        tags: ['娱乐', '电影']
      },
      {
        id: '7',
        type: 'expense',
        category: '医疗',
        description: '感冒药',
        amount: '35.80',
        date: '2024-01-11',
        tags: ['医疗', '药品']
      },
      {
        id: '8',
        type: 'income',
        category: '奖金',
        description: '年终奖',
        amount: '15000.00',
        date: '2024-01-08',
        tags: ['收入', '奖金']
      }
    ]
  },

  onLoad(options) {
    this.initPage()
  },
  // 初始化页面
  async initPage() {
    const { accountList, accountIndex } = await app.getAccountGlobal();
    this.setData({
      billList: accountList,
      selectedBill: accountList[accountIndex],
      selectedBillIndex: accountIndex // 新增
    })
    this.initDate()
    this.loadRecordList()
  },

  // 初始化日期
  initDate() {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1
    const lastMonth = currentMonth === 1 ? 12 : currentMonth - 1
    const lastMonthYear = currentMonth === 1 ? currentYear - 1 : currentYear
    
    this.setData({
      selectedYear: currentYear.toString(),
      selectedMonth: lastMonth.toString().padStart(2, '0'),
      selectedDate: `${lastMonthYear}-${lastMonth.toString().padStart(2, '0')}`
    })
  },

  // 显示账单按钮点击
  clickShowBillSelector() {
    this.setData({
      showBillSelector: true
    })
  },

  // 新增：account-selector组件选择账单事件
  onSelectBill(e) {
    const idx = e.detail.index;
    const bill = this.data.billList[idx];
    this.setData({
      selectedBill: bill,
      selectedBillIndex: idx,
      pageNum: 1
    });
    this.loadRecordList();
  },

  // 切换Tab
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      activeTab: tab,
      pageNum: 1,
      recordList: []
    })
    
    // 根据Tab类型设置默认日期
    if (tab === 'yearly') {
      const currentYear = new Date().getFullYear()
      this.setData({
        selectedYear: currentYear.toString(),
        selectedDate: `${currentYear}-01`
      })
    } else if (tab === 'monthly') {
      const now = new Date()
      const currentYear = now.getFullYear()
      const lastMonth = now.getMonth() === 0 ? 12 : now.getMonth()
      const lastMonthYear = now.getMonth() === 0 ? currentYear - 1 : currentYear
      this.setData({
        selectedYear: lastMonthYear.toString(),
        selectedMonth: lastMonth.toString().padStart(2, '0'),
        selectedDate: `${lastMonthYear}-${lastMonth.toString().padStart(2, '0')}`
      })
    }
    
    this.loadRecordList()
  },

  // 日期选择器变化
  onDateChange(e) {
    const dateValue = e.detail.value
    const [year, month] = dateValue.split('-')
    
    this.setData({
      selectedDate: dateValue,
      selectedYear: year,
      selectedMonth: month || '01',
      pageNum: 1,
      recordList: []
    })
    
    this.loadRecordList()
  },
  // 删除后处理
  async afterDeleteHandler() {
    this.setData({
      pageNum: 1,
      recordList: []
    })
    this.loadRecordList()
  },

  // 加载记录列表
  async loadRecordList() {
    if (this.data.loading) return
    this.setData({ loading: true })
    const currentPageNum = this.data.pageNum;
    try {
      let res = null
      const params = {
        current: currentPageNum,
        size: this.data.pageSize,
        accountBookId: this.data.selectedBill.id
      }
      // 根据不同的Tab调用不同的接口
      switch (this.data.activeTab) {
        case 'pending':
          res = await financeBill.getPendingBillRecords(params)
          break
        case 'yearly':
          params.year = this.data.selectedYear
          res = await financeBill.getYearlyBillRecords(params)
          break
        case 'monthly':
          params.yearMonth = this.data.selectedYear + '-' + this.data.selectedMonth
          res = await financeBill.getMonthlyBillRecords(params)
          break
        default:
          console.log('没有找到对应的Tab')
      }

      if (!res || !Array.isArray(res.records)) {
        wx.showToast({title: '获取记录列表返回结果异常', icon: 'none' });
        this.setData({ loading: false })
        return
      }
      // 字段映射与index页面保持一致
      const recordList = (res.records || []).map(item => ({
        id: item.id || item.accountBookId, // 若无id则用accountBookId
        type: item.financeType, // 'expense' or 'income'
        category: item.categoryName,
        categoryCode: item.categoryCode,
        financeDesc: item.financeDesc || '',
        amount: item.totalAmount,
        paymentMethod: item.paymentMethod,
        financeDate: item.financeDate,
        financeTime: item.financeTime,
        details: [],
        expanded: false
      }))
      const newRecordList = (currentPageNum && currentPageNum > 1) ? [...this.data.recordList, ...recordList] : recordList
      const total = typeof res.total === 'number' ? res.total : null;
      let hasMore;
      if (total !== null) {
        hasMore = (newRecordList.length < total);
      } else {
        hasMore = (recordList.length === this.data.pageSize);
      }
      let summary = null;
      if (this.data.activeTab === 'yearly' || this.data.activeTab === 'monthly') {
        summary = res.others || null;
      }
      this.setData({
        recordList: newRecordList,
        loading: false,
        hasMore: hasMore,
        pageNum: currentPageNum || 1,
        summary: summary
      })
    } catch (e) {
      console.error('获取记录列表失败:', e)
      wx.showToast({ title:  (e && e.data && e.data.msg) || '获取记录列表失败', icon: 'none' });
      this.setData({ loading: false })
    }
  },

  // 加载更多
  loadMore() {
    if (this.data.loading || !this.data.hasMore) return
    const nextPage = this.data.pageNum + 1
    this.setData({
      pageNum: nextPage
    })
    this.loadRecordList()
  },

  // 下拉刷新
  onRefresh() {
    this.setData({
      refreshing: true,
      pageNum: 1,
      recordList: []
    })
    
    setTimeout(() => {
      this.loadRecordList()
      this.setData({
        refreshing: false
      })
    }, 1000)
  }
}) 